package cn.gailvlun.gll.presentation.emotion;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RadioGroup;

import com.blankj.utilcode.util.KeyboardUtils;
import com.github.markzhai.recyclerview.BaseViewAdapter;
import com.jakewharton.rxbinding2.view.RxView;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import cn.gailvlun.gll.R;
import cn.gailvlun.gll.bean.PlaceHolder;
import cn.gailvlun.gll.databinding.ActivityEmotionDetailBinding;
import cn.gailvlun.gll.net.HttpMethods;
import cn.gailvlun.gll.net.HttpSubscriber;
import cn.gailvlun.gll.net.ListRes;
import cn.gailvlun.gll.net.emotion.Comment;
import cn.gailvlun.gll.net.emotion.CommentHeartReq;
import cn.gailvlun.gll.net.emotion.CommentReplyReq;
import cn.gailvlun.gll.net.emotion.Emotion;
import cn.gailvlun.gll.net.emotion.EmotionHeartReq;
import cn.gailvlun.gll.presentation.base.BaseActivity;
import cn.gailvlun.gll.presentation.chat.PhotoListActivity;
import cn.gailvlun.gll.presentation.emotion.bean.EmotionDetail;
import cn.gailvlun.gll.presentation.emotion.bean.EmotionDetailTransfer;
import cn.gailvlun.gll.presentation.emotion.util.EmotionDateUtil;
import cn.gailvlun.gll.presentation.emotion.widget.EmotionDetailDecoration;
import cn.gailvlun.gll.presentation.profile.OtherProfileActivity;
import cn.gailvlun.gll.presentation.profile.ProfileActivity;
import cn.gailvlun.gll.util.DialogUtil;
import cn.gailvlun.gll.util.LogUtil;
import cn.gailvlun.gll.util.ProfileUtil;
import cn.gailvlun.gll.util.RxUtil;
import cn.gailvlun.gll.widget.BasePopupWindow;
import cn.gailvlun.gll.widget.NavigationBarView;
import io.reactivex.functions.Consumer;



@Deprecated
public class EmotionDetailActivity extends BaseActivity {

    private ActivityEmotionDetailBinding mBinding;
    private EmotionDetailAdapter mAdapter;
    private EmotionDetail emotionDetail;

    public static void openActivity(Context context, @NonNull EmotionDetailTransfer transfer) {
        Intent i = new Intent(context, EmotionDetailActivity.class);
        i.putExtra("data", transfer);
        context.startActivity(i);
    }

    public static void openFromNotification(Context context, @NonNull EmotionDetailTransfer transfer) {
        Intent i = new Intent(context, EmotionDetailActivity.class);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        i.putExtra("data", transfer);
        context.startActivity(i);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        setIntent(intent);

        loadTransfer();


        loadData(null);

    }

    private void loadTransfer() {
        EmotionDetailTransfer data = (EmotionDetailTransfer) getIntent().getSerializableExtra("data");
        emotionDetail = new EmotionDetail(data);

        if (mBinding != null) {
            if (data.getTitle() != 0) {
                mBinding.navigationBar.setTitleText(getString(data.getTitle()));
            }
            mAdapter.clear();
            mBinding.srl.setEnableLoadmore(false);
        }
    }

    @Override
    protected void initComponent() {
        EmotionDetailTransfer data = (EmotionDetailTransfer) getIntent().getSerializableExtra("data");
        emotionDetail = new EmotionDetail(data);

        getWindow().setSoftInputMode
                (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN |
                        WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_emotion_detail);
        if (data.getTitle() != 0) {
            mBinding.navigationBar.setTitleText(getString(data.getTitle()));
        }
        mAdapter = new EmotionDetailAdapter(this);
        mBinding.rvEmotionDetailList.setAdapter(mAdapter);
        mBinding.rvEmotionDetailList.setLayoutManager(new LinearLayoutManager(this));
        mBinding.rvEmotionDetailList.addItemDecoration(new EmotionDetailDecoration(this));
        mAdapter.setPresenter(new Presenter());
        mBinding.etReply.setTag(-1);

        mBinding.srl.setEnableLoadmore(false);
    }

    @Override
    protected void createHandler() {
        mBinding.navigationBar.setOnBackListener(new NavigationBarView.OnBackListener() {
            @Override
            public void onBack(NavigationBarView nb) {
                onBackPressed();
            }
        });
        mBinding.srl.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                loadComment();
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                emotionDetail.getQueryParam().setLastId(null);
                loadComment();
            }
        });
        RxTextView.textChanges(mBinding.etReply).subscribe(new Consumer<CharSequence>() {
            @Override
            public void accept(CharSequence charSequence) throws Exception {
                mBinding.tvReply.setEnabled(charSequence.toString().trim().length() > 0);
                saveReply(charSequence.toString());
            }
        });
        RxView.clicks(mBinding.tvReply)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        replyComment(mBinding.tvReply);
                    }
                });
        mBinding.etReply.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mBinding.etReply.isFocused()) {
                    emotionDetail.getReq().setReply_id(null);
                    LogUtil.d("etReply.onClick");
                    restoreReplyContent(-1);
                }
            }
        });
        KeyboardUtils.registerSoftInputChangedListener(this, new KeyboardUtils.OnSoftInputChangedListener() {
            @Override
            public void onSoftInputChanged(int height) {
                if (!KeyboardUtils.isSoftInputVisible(mContext)) {

                    mBinding.etReply.setTag(null);
                    mBinding.etReply.setText(null);
                    mBinding.etReply.setHint(R.string.emotion_what_is_your_reply);
                    mBinding.etReply.setFocusable(false);
                    mBinding.etReply.setFocusableInTouchMode(false);
                }
            }
        });
    }

    private Dialog pd;

    @Override
    protected void loadData(@Nullable Bundle savedInstanceState) {
        pd = DialogUtil.showIndeterminate(mContext);
        HttpMethods.getEmotionService().emotionDetail(emotionDetail.getTransfer().getId())
                .compose(RxUtil.<Emotion>applyScheduler())
                .compose(this.<Emotion>bindToLifecycle())
                .subscribe(new HttpSubscriber<Emotion>() {
                    @Override
                    protected void onSuccess(Emotion response) {
                        resetHeader(response);
                        loadComment();
                    }

                    @Override
                    protected void onFailure(String errMsg, @Nullable Emotion response, int code) {
                        DialogUtil.showError(mContext, errMsg);
                        pd.dismiss();
                    }
                });
    }

    private void loadComment() {
        HttpMethods.getEmotionService()
                .commentList(emotionDetail.getTransfer().getId(),
                        emotionDetail.getQueryParam().getLastId(),
                        emotionDetail.getQueryParam().getDirection(),
                        emotionDetail.getOrder().getDesc())
                .compose(RxUtil.<ListRes<Comment>>applyScheduler())
                .subscribe(new HttpSubscriber<ListRes<Comment>>() {
                    @Override
                    protected void onSuccess(ListRes<Comment> response) {
                        emotionDetail.getEmotion().setComment_num(response.getCount());
                        mBinding.srl.setEnableLoadmore(response.isNext());
                        if (emotionDetail.getQueryParam().getLastId() == null) {
                            resetHeader(emotionDetail.getEmotion());
                        }
                        if (response.getResults().isEmpty()) {
                            mAdapter.add(null, EmotionDetailAdapter.Type.EMPTY.ordinal());
                        } else {
                            mAdapter.addAll(response.getResults(), EmotionDetailAdapter.Type.COMMENT.ordinal());
                            emotionDetail.getQueryParam().setLastId(response.getResults().get(response.getResults().size() - 1).getId());
                        }
                        mBinding.srl.finishRefresh();
                        mBinding.srl.finishLoadmore();
                    }

                    @Override
                    protected void onFailure(String errMsg, @Nullable ListRes<Comment> response, int code) {
                        mBinding.srl.finishRefresh();
                        mBinding.srl.finishLoadmore();
                    }

                    @Override
                    protected void onFinish() {
                        super.onFinish();
                        pd.dismiss();
                    }
                });
    }


    private void restoreReplyContent(int key) {

        String reply = emotionDetail.getReplyCache().get(key);
        mBinding.etReply.setFocusable(true);
        mBinding.etReply.setFocusableInTouchMode(true);
        mBinding.etReply.setTag(key);
        LogUtil.d("[[[[[[[[[[[key: " + key + ";;;reply: " + reply + "]]]]]]]]]]");
        if (TextUtils.isEmpty(reply)) {
            mBinding.etReply.setText(null);
        } else {
            mBinding.etReply.setText(reply);
            mBinding.etReply.setSelection(reply.length());
        }
        KeyboardUtils.showSoftInput(mBinding.etReply);
    }

    
    private void saveReply(String reply) {
        if (mBinding.etReply.getTag() != null) {
            emotionDetail.getReplyCache().put((Integer) mBinding.etReply.getTag(), reply);
        }
    }

    private void replyComment(View v) {
        pd = DialogUtil.showIndeterminate(mContext);

        String text = mBinding.etReply.getText().toString();
        final CommentReplyReq req = emotionDetail.getReq();
        req.setText(text);
        req.setRecord_id(emotionDetail.getEmotion().getId());

        HttpMethods.getEmotionService().commentReply(emotionDetail.getReq())
                .compose(RxUtil.<Comment>applyScheduler())
                .compose(this.<Comment>bindToLifecycle())
                .subscribe(new HttpSubscriber<Comment>() {
                    @Override
                    protected void onSuccess(Comment response) {
                        emotionDetail.getEmotion().setComment_num(
                                emotionDetail.getEmotion().getComment_num() + 1
                        );
                        int position = mAdapter.findFirstPositionByViewType(EmotionDetailAdapter.Type.COMMENT);
                        if (position == -1) {
                            mAdapter.add(response, EmotionDetailAdapter.Type.COMMENT.ordinal());
                            mAdapter.removeByViewType(EmotionDetailAdapter.Type.EMPTY);
                        } else {
                            mAdapter.add(position, response, EmotionDetailAdapter.Type.COMMENT.ordinal());
                        }
                        mAdapter.notifyDataSetChanged();
                        mBinding.etReply.setText(null);
                        emotionDetail.getReq().setReply_id(null);
                        emotionDetail.getReq().setText(null);
                        mBinding.etReply.setHint(R.string.emotion_what_is_your_reply);
                    }

                    @Override
                    protected void onFailure(String errMsg, @Nullable Comment response, int code) {
                        DialogUtil.showError(mContext, errMsg);
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        pd.dismiss();
                    }
                });
    }

    private void commentHeart(final Comment c) {
        int heart = c.getHeart().isHearted() ? -1 : 1;
        CommentHeartReq req = new CommentHeartReq(c.getId(), heart);
        HttpMethods.getEmotionService()
                .commentHeart(req)
                .compose(RxUtil.<Comment>applyScheduler())
                .subscribe(new HttpSubscriber<Comment>() {
                    @Override
                    protected void onSuccess(Comment response) {
                        c.setHeart(response.getHeart());
                        mAdapter.notifyDataSetChanged();
                    }

                    @Override
                    protected void onFailure(String errMsg, @Nullable Comment response, int code) {

                    }
                });
    }

    private void resetHeader(Emotion emotion) {
        emotionDetail.setEmotion(emotion);
        mAdapter.clear();
        mAdapter.add(emotion, EmotionDetailAdapter.Type.EMOTION.ordinal());
        mAdapter.add(emotion, EmotionDetailAdapter.Type.COMMENT_HEADER.ordinal());
    }

    public class Presenter implements BaseViewAdapter.Presenter {
        public void jump2Profile(Emotion item) {
            Integer myId = ProfileUtil.getUserId();
            if (myId != null && item.getOwner().getId() == myId) {
                ProfileActivity.openActivity(mContext);
            } else {
                OtherProfileActivity.openActivity(mContext, item.getOwner());
            }
        }

        public void jump2Profile(Comment item) {
            Integer myId = ProfileUtil.getUserId();
            if (myId != null && item.getOwner().getId() == myId) {
                ProfileActivity.openActivity(mContext);
            } else {
                OtherProfileActivity.openActivity(mContext, item.getOwner());
            }
        }

        public String getTime(Date time) {
            return EmotionDateUtil.commentTimeFormat(time);
        }

        public Spanned getCommentContent(Comment c) {
            int focusColor = mContext.getResources().getColor(R.color.apricot);
            String text = (c.getReply() == null) ? c.getText()
                    : getString(R.string.emotion_comment_reply_mode,
                    focusColor,
                    c.getReply().getName(),
                    c.getText());
            return Html.fromHtml(text);
        }

        public void replyTo(Comment c) {
            String text = getString(R.string.emotion_comment_hint_mode, c.getOwner().getName());
            mBinding.etReply.setHint(Html.fromHtml(text));
            emotionDetail.getReq().setReply_id(c.getOwner().getId());
            restoreReplyContent(c.getId());
        }

        public void commentHeart(Comment c) {
            EmotionDetailActivity.this.commentHeart(c);
        }

        public void emotionHeart(final Emotion emotion) {
            EmotionHeartReq req = new EmotionHeartReq(emotion.getId(), emotion.getHeart().isHearted() ? -1 : 1);
            HttpMethods.getEmotionService().emotionHeart(req)
                    .compose(RxUtil.<Emotion>applyScheduler())
                    .subscribe(new HttpSubscriber<Emotion>() {
                        @Override
                        protected void onSuccess(Emotion response) {
                            
                            emotion.setHeart(response.getHeart());
                            mAdapter.notifyDataSetChanged();
                        }

                        @Override
                        protected void onFailure(String errMsg, @Nullable Emotion response, int code) {
                            DialogUtil.showError(mContext, errMsg);
                        }
                    });
        }

        public void onPhotoClick(ImageView igv, List<String> photos, int position) {




            PhotoListActivity.openActivity(mContext, new ArrayList<>(photos), position);
        }

        public String getFilterText(Emotion item) {
            if (emotionDetail.getOrder() == EmotionDetail.Order.CREATED) {
                return getString(R.string.emotion_sort_by_time);
            } else {
                return getString(R.string.emotion_sort_by_hot);
            }
        }

        public void onFilter(View view) {
            View popView = LayoutInflater.from(mContext).inflate(R.layout.popup_filter, null);
            RadioGroup rg = popView.findViewById(R.id.rg_order);
            final BasePopupWindow popupWindow = new BasePopupWindow(mContext);
            popupWindow.setContentView(popView);
            
            switch (emotionDetail.getOrder()) {
                case CREATED: {
                    rg.check(R.id.rb_time);
                    break;
                }
                case HEART_LEN: {
                    rg.check(R.id.rb_hot);
                    break;
                }
            }
            
            rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(RadioGroup group, int checkedId) {
                    switch (checkedId) {
                        case R.id.rb_time: {
                            emotionDetail.setOrder(EmotionDetail.Order.CREATED);
                            break;
                        }
                        case R.id.rb_hot: {
                            emotionDetail.setOrder(EmotionDetail.Order.HEART_LEN);
                            break;
                        }
                    }
                    popupWindow.dismiss();
                    mBinding.srl.autoRefresh();
                }
            });

            popupWindow.showAsDropDown(view);
        }

        public void onDelete(final Comment comment) {
            HttpMethods.getEmotionService()
                    .deleteComment(comment.getId())
                    .compose(RxUtil.<PlaceHolder>applyScheduler())
                    .subscribe(new HttpSubscriber<PlaceHolder>() {
                        @Override
                        protected void onSuccess(PlaceHolder response) {
                            mAdapter.removeComment(comment);
                        }

                        @Override
                        protected void onFailure(String errMsg, @Nullable PlaceHolder response, int code) {
                            DialogUtil.showError(mContext, errMsg);
                        }
                    });
        }
    }

    public static class Util {
        public static int getDeletionVisibility(Comment comment) {
            if (comment.getOwner().getId() == ProfileUtil.getUserId()) {
                return View.VISIBLE;
            } else {
                return View.GONE;
            }
        }
    }
}
